<?php
/**
 * Created by PhpStorm.
 * User: yearnfar<207736107@qq.com>
 * Date: 2015/4/27 0027
 * Time: 下午 6:21
 */

namespace Yearnfar\Bundle\CmsBundle\Controller;


use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class BaseController extends Controller{

    const UPLOAD_IMAGE_DIR = '/../web/upload/image';


    /**
     * 信息提示
     * @param $msg
     * @param string $redirect
     * @param string $class
     * @param int $time
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function msgOut($msg, $redirect='', $class='', $time=1)
    {
        if ($redirect=='') $redirect = $this->get('request')->server->get('HTTP_REFERER', '/');
        return $this->render('CmsBundle::msg.html.twig', ['msg'=>$msg, 'redirect'=>$redirect, 'time'=>$time, 'class'=>$class]);
    }

    /**
     * 输出JSON格式数据
     * @param $data
     * @param int $errno
     * @param string $errmsg
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function jsonOut($data, $errno=0, $errmsg='')
    {
        if ($errno!==false) {
            $content = json_encode(['data'=>$data, 'errno'=>$errno, 'errmsg'=>$errmsg]);
        } else {
            $content = json_encode($data);
        }
        return $this->render('CmsBundle::json.html.twig', ['content' => $content]);
    }

    /**
     * 遍历所有分类
     * @param $term
     * @param $ats
     * @param int $tid
     * @param int $depth
     * @param string $prefix
     * @param string $pName
     */
    protected function enumTerm(&$term, $ats, $tid=0, $depth=0, $prefix='——', $pName='/')
    {
        $depth++;
        foreach ($ats as $at) {
            if ($at->getPid()==$tid) {
                $at->name2 = str_repeat($prefix, $depth). $at->getName();
                $at->pName = $pName;
                $term[] = $at;

                $this->enumTerm($term, $ats, $at->getId(), $depth, $prefix, $at->getName());
            }
        }
    }

    /**
     * 递归删除目录和目录下面的文件
     * @param $dir
     */
    protected function enumRmDir($dir)
    {
        if (!is_dir($dir)) {
            return ;
        }

        $dir = rtrim($dir, '\\/') . '/';
        $dh  = opendir($dir);

        while ($fn=readdir($dh)) {
            if($fn!="." && $fn!="..") {
                $path = $dir."/".$fn;

                if(!is_dir($path)) {
                    unlink($path);
                } else {
                    $this->enumRmDir($path);
                }
            }
        }

        rmdir($dir);
    }
}